﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CHS.ChengDu.Service;
using CHS.ChengDu.Dtos;
using Com.WebApiServe.Service;
using ChengDu.Com.WebApiService;
using System.Net.Http;
using Newtonsoft.Json;
using System.Text.Json;
using System.Net.NetworkInformation;
using CHS.ChongQing.Service;

namespace CHS.ChengDu.WebApiService
{
    public partial class ServiceConfig : Form
    {
        public ServiceConfig()
        {
            InitializeComponent();
            rtb_input.Text = "";
        }
        /// <summary>
        /// web服务
        /// </summary>
        private HttpService _httpService;
        /// <summary>
        /// web请求客户端
        /// </summary>
        private static readonly HttpClient _httpClient = new HttpClient();
        /// <summary>
        /// 启动http服务
        /// </summary>
        private async Task StartService()
        {
            string port = this.tb_port.Text;
            if (string.IsNullOrEmpty(port))
            {
                this.tb_port.Text = "9001";
                port = "9001";
            }
            _httpService = new HttpService(int.Parse(port));
            await _httpService.StartHttpServer();
        }
        /// <summary>
        /// 关闭http服务
        /// </summary>
        public async Task StopService()
        {
            await _httpService.CloseHttpServer();
            _httpService.Dispose();
        }

        private async void ServiceConfig_Load(object sender, EventArgs e)
        {
            AutoStart _autoStart = new AutoStart();

            //设置开机自动启动
            if (_autoStart.CheckAutoStart())
            {
                this.cb_auto_start.Checked = true;
                _autoStart.SetAutoStart();
            }

            //启动服务
            await StartService();

            this.Hide();
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void ServiceConfig_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall)
            {
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void cb_auto_start_CheckedChanged(object sender, EventArgs e)
        {
            AutoStart _autoStart = new AutoStart();


            if (this.cb_auto_start.Checked == true)
            {
                _autoStart.SetAutoStart();
            }
            else
            {

            }
        }
        /// <summary>
        /// 最小化托盘按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
            else
            {
                notifyIcon1.Visible = true;
                this.Show();
                this.Activate();
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var _value = ConfigManager.GetValue("setting", "localLog");
            var output = ConfigManager.SetValue("serviceSetting", "url", "123");
            MessageBox.Show(_value);
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            bool loaclLog = this.cb_auto_log.Checked;
            bool autoStart = this.cb_auto_start.Checked;
            string port = this.tb_port.Text;
            if (string.IsNullOrWhiteSpace(port))
            {
                MessageBox.Show("请输入本地服务端口");
                return;
            }

        }
        #region COM接口的测试
        /// <summary>
        /// COM初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Test_Click(object sender, EventArgs e)
        {
            CHSChengDu _chs = new CHSChengDu();
            int appcode = 0;
            string appmsg = "";
            _chs.CHS_Init(ref appcode, ref appmsg);
            this.rtb_output.Text = "appcode:" + appcode + "\nappmsg:" + appmsg;
        }
        /// <summary>
        /// 调用安全控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_call_Click(object sender, EventArgs e)
        {
            CHSChengDu _chs = new CHSChengDu();

            string _infono, _input, _output;
            _infono = this.tb_infono.Text;
            _input = this.rtb_input.Text;
            _output = "";

            var status = _chs.CHS_Call(_infono, _input, ref _output);
            this.rtb_output.Text = _output;
        }
        /// <summary>
        /// 释放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_destroy_Click(object sender, EventArgs e)
        {
            CHSChengDu _chs = new CHSChengDu();
            _chs.CHS_Destroy();
            this.rtb_output.Text = "COM接口已释放";
        }


        private void btn_print_Click(object sender, EventArgs e)
        {
            string _input = "";

            CHSChengDu _chs = new CHSChengDu();
            string _output;
            _input = this.rtb_input.Text;
            _output = "";
            _chs.CHS_Pint(_input, ref _output);
            this.rtb_output.Text = _output;
        }


        #endregion

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 重启服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private async void btn_restart_Click(object sender, EventArgs e)
        {
            await StopService();
            await StartService();

        }

        #region Api请求测试

        private async void btn_api_init_Click(object sender, EventArgs e)
        {
            string port = this.tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHS/Init";
            var _result = await _httpClient.PostAsync(url, new StringContent("", Encoding.UTF8, "application/json"));
            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + "空";
            message += "\nPOST请求结果:" + await _result.Content.ReadAsStringAsync();
            this.rtb_output.Text = message;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_api_call_Click(object sender, EventArgs e)
        {
            CHSCallInputDto _input = new CHSCallInputDto()
            {
                infno = this.tb_infono.Text,
                input = this.rtb_input.Text
            };

            var _inputContent = JsonConvert.SerializeObject(_input);

            string port = this.tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHS/Call";
            var _result = await _httpClient.PostAsync(url, new StringContent(_inputContent, Encoding.UTF8, "application/json"));

            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + _inputContent;
            message += "\nPOST请求结果:" + await _result.Content.ReadAsStringAsync();
            this.rtb_output.Text = message;
        }

        /// <summary>
        /// 释放接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_api_destroy_Click(object sender, EventArgs e)
        {
            string port = this.tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHS/Destory";
            var _result = await _httpClient.PostAsync(url, new StringContent("", Encoding.UTF8, "application/json"));
            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + "空";
            message += "\nPOST请求结果:" + "空";
            this.rtb_output.Text = message;
        }
        /// <summary>
        /// API打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_api_print_Click(object sender, EventArgs e)
        {

            CHSCallInputDto _inputDto = new CHSCallInputDto()
            {
                input = this.rtb_input.Text
            };

            var _inputContent = JsonConvert.SerializeObject(_inputDto);

            string port = this.tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHS/Print";
            var _result = await _httpClient.PostAsync(url, new StringContent(_inputContent, Encoding.UTF8, "application/json"));

            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + _inputContent;
            message += "\nPOST请求结果:" + await _result.Content.ReadAsStringAsync();

            this.rtb_output.Text = message;
        }
        #endregion
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_sign_Click(object sender, EventArgs e)
        {
            var _input = new CHSEncryptionInput()
            {
                PublicKey = rt_public_key.Text,
                PrivateKey = rt_private_key.Text,
                UserId = "",
                Input = rt_input.Text
            };

            var _output = CHSEncryption.gm_sign_key(_input);
            rt_output.Text = _output.output;
            tb_code.Text = _output.Code.ToString();
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_encrypt_Click(object sender, EventArgs e)
        {
            var _input = new CHSEncryptionInput()
            {
                PublicKey = rt_public_key.Text,
                PrivateKey = rt_private_key.Text,
                UserId = "",
                Input = rt_input.Text
            };

            var _output = CHSEncryption.gm_ecb_encrypt_key(_input);
            rt_output.Text = _output.output;
            tb_code.Text = _output.Code.ToString();
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_decrypt_Click(object sender, EventArgs e)
        {
            var _input = new CHSEncryptionInput()
            {
                PublicKey = rt_public_key.Text,
                PrivateKey = rt_private_key.Text,
                UserId = "",
                Input = rt_output.Text
            };

            var _output = CHSEncryption.gm_ecb_decrypt_key(_input);
            rt_input.Text = _output.output;
            tb_code.Text = _output.Code.ToString();
        }

        /// <summary>
        /// 签名api测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_signin_api_Click(object sender, EventArgs e)
        {
            var _input = new CHSEncryptionInput()
            {
                PublicKey = rt_public_key.Text,
                PrivateKey = rt_private_key.Text,
                UserId = "",
                Input = rt_input.Text
            };

            string port = tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHS/SignIn";
            string parms = JsonConvert.SerializeObject(_input);

            var _result = await _httpClient.PostAsync(url, new StringContent(parms, Encoding.UTF8, "application/json"));
            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + parms;
            message += "\nPOST请求结果:" + await _result.Content.ReadAsStringAsync();
            this.rt_output.Text = message;
        }

        private async void btn_encrypt_api_Click(object sender, EventArgs e)
        {
            var _input = new CHSEncryptionInput()
            {
                PublicKey = rt_public_key.Text,
                PrivateKey = rt_private_key.Text,
                UserId = "",
                Input = rt_input.Text
            };

            string port = tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHS/Encrypt";
            string parms = JsonConvert.SerializeObject(_input);

            var _result = await _httpClient.PostAsync(url, new StringContent(parms, Encoding.UTF8, "application/json"));
            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + parms;
            message += "\nPOST请求结果:" + await _result.Content.ReadAsStringAsync();
            this.rt_output.Text = message;
        }

        private async void btn_api_decrypt_Click(object sender, EventArgs e)
        {
            var _input = new CHSEncryptionInput()
            {
                PublicKey = rt_public_key.Text,
                PrivateKey = rt_private_key.Text,
                UserId = "",
                Input = rt_input.Text
            };

            string port = tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHS/Decrypt";
            string parms = JsonConvert.SerializeObject(_input);

            var _result = await _httpClient.PostAsync(url, new StringContent(parms, Encoding.UTF8, "application/json"));
            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + parms;
            message += "\nPOST请求结果:" + await _result.Content.ReadAsStringAsync();
            this.rt_output.Text = message;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            CHSBusinessService cq = new CHSBusinessService();
            //rtb_input.Text = "{\"infno\":\"9001\",\"msgid\":\"H50010504793202411182124060001\",\"mdtrtarea_admvs\":\"500105\",\"insuplc_admdvs\":\"500105\",\"recer_sys_code\":\"FSI_LOCAL\",\"dev_no\":\"\",\"dev_safe_info\":\"\",\"cainfo\":\"\",\"signtype\":\"\",\"infver\":\"V1.0\",\"opter_type\":\"1\",\"opter\":\"0\",\"inf_time\":\"2024-11-18 21:24:06\",\"fixmedins_code\":\"H50010504793\",\"fixmedins_name\":\"重庆景城胃肠医院\",\"sign_no\":\"\",\"input\":{\"signIn\":{\"Id\":0,\"opter_no\":\"9999\",\"mac\":\"902E16B2C3D8\",\"ip\":\"0.0.0.1\",\"sign_time\":\"0001-01-01 00:00:00\",\"IsDelete\":false}}}";
            var output = cq.CallService(new ChongQing.Service.CHSBaseInput
            {
                Input = rtb_input.Text
            });

            //var output = cq.callCqService();

            MessageBox.Show(JsonConvert.SerializeObject(output));
            rtb_output.Text = JsonConvert.SerializeObject(output);
        }

        private async void button2_Click(object sender, EventArgs e)
        {
           // rtb_input.Text = "{\"infno\":\"9001\",\"msgid\":\"H50010504793202411182124060001\",\"mdtrtarea_admvs\":\"500105\",\"insuplc_admdvs\":\"500105\",\"recer_sys_code\":\"FSI_LOCAL\",\"dev_no\":\"\",\"dev_safe_info\":\"\",\"cainfo\":\"\",\"signtype\":\"\",\"infver\":\"V1.0\",\"opter_type\":\"1\",\"opter\":\"0\",\"inf_time\":\"2024-11-18 21:24:06\",\"fixmedins_code\":\"H50010504793\",\"fixmedins_name\":\"重庆景城胃肠医院\",\"sign_no\":\"\",\"input\":{\"signIn\":{\"Id\":0,\"opter_no\":\"9999\",\"mac\":\"902E16B2C3D8\",\"ip\":\"0.0.0.1\",\"sign_time\":\"0001-01-01 00:00:00\",\"IsDelete\":false}}}";

            CHSBaseInput _input = new CHSBaseInput
            {
                Input = rtb_input.Text
            };

            string port = tb_port.Text;
            string url = "http://127.0.0.1:" + port + "/Api/CHSCQ/CallService";
            string parms = JsonConvert.SerializeObject(_input);

            var _result = await _httpClient.PostAsync(url, new StringContent(parms, Encoding.UTF8, "application/json"));
            string message = "";
            message += "POST请求地址:" + url;
            message += "\nPOST请求参数:" + parms;
            message = await _result.Content.ReadAsStringAsync();
            MessageBox.Show(message);
            rtb_output.AppendText(message);
        }
    }
}
